package com.zxlfysj.huffmantree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 赫夫曼树
 *
 * @author yangshujing
 * @create 2020-08-20 11:01
 */
public class HuffmanTree {
    public static void main(String[] args) {
        int[] arr = {13, 7, 8, 3, 29, 6, 1};
        //创建赫夫曼树
        Node root = createHuffmanTree(arr);
        //前序遍历，验证创建的赫夫曼树
        preOrder(root);

    }

    //创建赫夫曼树方法
    public static Node createHuffmanTree(int[] arr) {
        List<Node> nodes = new ArrayList<>();
        for(int value : arr) {
            nodes.add(new Node(value));
        }
        while(nodes.size() > 1) {
            //升序排序
            Collections.sort(nodes);
            //取出两个最小权值的结点组合成以权值之和为父节点的子树
            Node leftNode = nodes.get(0);
            Node rightNode = nodes.get(1);
            Node parent = new Node(leftNode.value + rightNode.value);
            parent.left = leftNode;
            parent.right = rightNode;
            nodes.remove(leftNode);
            nodes.remove(rightNode);
            nodes.add(parent);
        }
        return nodes.get(0);
    }

    public static void preOrder(Node root) {
        if(root != null) {
            root.preOrder();
        } else {
            System.out.println("空树，无法遍历");
        }
    }
}

class Node implements Comparable<Node> {
    int value; //结点权值
    Node left;
    Node right;

    public Node(int value) {
        this.value = value;
    }

    //前序遍历
    public void preOrder() {
        System.out.println(this);
        if(this.left != null) {
            this.left.preOrder();
        }
        if(this.right != null) {
            this.right.preOrder();
        }
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    @Override
    public int compareTo(Node o) {
        return this.value - o.value;
    }
}
